package com.example.factory.api.dto.assembler;

import com.example.factory.api.dto.DtoEquipment;
import com.example.factory.api.dto.form.DtoEquipmentForm;
import com.example.factory.core.domain.Department;
import com.example.factory.core.domain.Equipment;
import com.example.factory.core.repository.DepartmentRepository;
import com.example.factory.core.repository.EquipmentRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Lei Tao
 */
@Component
public class EquipmentAssembler {
    private final EquipmentRepository equipmentRepository;
    private final DepartmentRepository departmentRepository;

    public EquipmentAssembler(EquipmentRepository equipmentRepository, DepartmentRepository departmentRepository) {
        this.equipmentRepository = equipmentRepository;
        this.departmentRepository = departmentRepository;
    }

    public List<DtoEquipment> toDtoEquipments(Page<Equipment> equipments) {
        List<Equipment> equipmentList = equipments.getContent();
        return equipmentList.stream().map(this::toDtoEquipment).collect(Collectors.toList());

    }

    public DtoEquipment toDtoEquipment(Equipment equipment) {
        DtoEquipment dtoEquipment = new DtoEquipment();
        BeanUtils.copyProperties(equipment, dtoEquipment);
        if (equipment.getDepartment()!=null){
            dtoEquipment.setDepartmentName(equipment.getDepartment().getName());
        }

        return dtoEquipment;
    }

    public Equipment toEquipment(DtoEquipmentForm dtoEquipmentForm) {
        Equipment equipment;
        if (!StringUtils.isEmpty(dtoEquipmentForm.getGuid())) {
            equipment = equipmentRepository.findByGuidAndArchivedFalse(dtoEquipmentForm.getGuid());
        } else {
            equipment = new Equipment();
        }
        BeanUtils.copyProperties(dtoEquipmentForm, equipment);
        if (!StringUtils.isEmpty(dtoEquipmentForm.getDepartmentGuid())) {
            Department department = departmentRepository.findByGuidAndArchivedFalse(dtoEquipmentForm.getDepartmentGuid());
            equipment.setDepartment(department);
        }
        return equipment;
    }
}
